package com.kmxd.ams.app.event.summary.command;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.ImmutableList;
import com.kmxd.ams.app.event.AmsEventPublisher;
import com.kmxd.ams.client.archive.IArchiveFieldSvc;
import com.kmxd.ams.client.arrange.IDocumentSvc;
import com.kmxd.ams.client.arrange.IVolumeSvc;
import com.kmxd.ams.client.event.es.EsUpdateDataEvent;
import com.kmxd.ams.client.event.summary.SummaryVolumeEvent;
import com.kmxd.ams.core.common.enums.ArchStatusEnum;
import com.kmxd.ams.core.common.enums.SummaryTypeEnum;
import com.kmxd.ams.core.util.ConvertUtil;
import com.kmxd.ams.core.util.DynamicTableNameUtil;
import com.kmxd.ams.infra.archive.entity.ArchiveField;
import com.kmxd.ams.infra.arrange.entity.Document;
import com.kmxd.ams.infra.arrange.entity.Volume;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 汇总卷内信息 按元数据汇总信息设置，进行信息汇总
 *
 * @author nickbi
 */
@Slf4j
@Component
@AllArgsConstructor
public class VolumeSummaryCmd {
  private final IVolumeSvc volumeSvc;
  private final IDocumentSvc documentSvc;
  private final IArchiveFieldSvc archiveFieldSvc;
  private final AmsEventPublisher amsEventPublisher;

  /** 复制电子文件 */
  public void summary(SummaryVolumeEvent event) {
    log.debug("start summary volume: {} ", event);
    Volume qry = new Volume();
    qry.setArchTypeId(event.getArchTypeId());
    qry.setTableId(event.getTableId());
    qry.setId(event.getId());
    Volume volume = volumeSvc.view(qry);
    if (null == volume) {
      return;
    }
    // 查询字段设置的统计字段信息
    LambdaQueryWrapper<ArchiveField> wrapper =
        Wrappers.<ArchiveField>lambdaQuery()
            .eq(ArchiveField::getArchTypeId, event.getArchTypeId())
            .eq(ArchiveField::getTableId, event.getTableId())
            .isNotNull(ArchiveField::getSummaryTableId)
            .isNotNull(ArchiveField::getSummaryType)
            .isNotNull(ArchiveField::getSummaryField);
    List<ArchiveField> fieldList = archiveFieldSvc.list(wrapper);
    if (null == fieldList || fieldList.isEmpty()) {
      return;
    }
    Map<String, Object> volumeMap = BeanUtil.beanToMap(volume);
    Document document = new Document();
    document.setVolId(volume.getId());
    document.setTableId(event.getDocTableId());
    document.setArchTypeId(event.getArchTypeId());
    fieldList.stream()
        // 过滤空字符串，多个filter编译后会优化，便于阅读代码可以分开编写
        .filter(item -> StringUtils.isNotBlank(item.getSummaryType()))
        .filter(item -> StringUtils.isNotBlank(item.getSummaryTableId()))
        .filter(item -> StringUtils.isNotBlank(item.getSummaryField()))
        .forEach(
            meta -> {
              Object summaryValue =
                  documentSvc.selectWithSummaryType(
                      document,
                      meta.getSummaryField(),
                      SummaryTypeEnum.convert(meta.getSummaryType()));
              volumeMap.put(StringUtils.underlineToCamel(meta.getDbFieldKey()), summaryValue);
            });
    Volume newVolume = ConvertUtil.toBean(volumeMap, Volume.class);
    newVolume.setTableId(event.getTableId());
    newVolume.setArchTypeId(event.getArchTypeId());
    if (newVolume.equals(volume)) {
      return;
    }
    DynamicTableNameUtil.setTableName(newVolume.getTableId());
    volumeSvc.updateById(newVolume);
    if (ObjectUtil.equals(newVolume.getStatus(), ArchStatusEnum.S1.getCode())) {
      amsEventPublisher.publishEvent(
          new EsUpdateDataEvent(
              ImmutableList.of(volume.getId()), volume.getArchTypeId(), volume.getTableId()));
    }
  }
}
